<script lang="ts" setup>
import { reactive, ref, onMounted } from 'vue';
import { ArrowDown, CloseBold } from '@element-plus/icons-vue';
import { getDictTypeList, queryCraftsCategoryList } from '@/server/api/biz';
import { useRouter } from 'vue-router';
import { ElMessage, ElMessageBox } from 'element-plus';
import { useI18n } from 'vue-i18n';
const { t } = useI18n();
const dropdown = ref();
const ruleFormRef = ref();
const isHideMore = ref(false);
const boardNum = ref('');
const pcbData = reactive({
  productId: '', // 板子类型
  boardLayer: '',
  pcbLength: '',
  pcbWidth: '',
  orderNumber: '', // 板子数量
  productList: [], //  产品列表
  pcbCraftsCategoryList: [],
  displayData: [],
  layerList: [], // 板层列表
  smtLayer: '',
  smtSolderJoint: '',
  patchType: '',
});
const router = useRouter();
const props = defineProps({
  data: {
    type: Object,
  },
});
const pcbRuleForm = reactive({
  name: '',
  region: '',
  count: '',
  date1: '',
  date2: '',
  delivery: false,
  type: [],
  resource: '',
  desc: '',
  countList: [5, 10, 15, 20, 25, 30, 35, 40, 45, 50, 100, 1000, 2000],
  selectCount: 5,
  isAtive: false,
});
const smtRuleForm = reactive({
  smtLayer: '',
  solderJoint: '',
  count: '',
  type: '',
});

const rules = reactive({
  name: [
    { required: true, message: 'Please input Activity name', trigger: 'blur' },
    { min: 3, max: 5, message: 'Length should be 3 to 5', trigger: 'blur' },
  ],
  region: [
    {
      required: true,
      message: 'Please select Activity zone',
      trigger: 'change',
    },
  ],
  count: [
    {
      required: true,
      message: 'Please select Activity count',
      trigger: 'change',
    },
  ],
  date1: [
    {
      type: 'date',
      required: true,
      message: 'Please pick a date',
      trigger: 'change',
    },
  ],
  date2: [
    {
      type: 'date',
      required: true,
      message: 'Please pick a time',
      trigger: 'change',
    },
  ],
  type: [
    {
      type: 'array',
      required: true,
      message: 'Please select at least one activity type',
      trigger: 'change',
    },
  ],
  resource: [
    {
      required: true,
      message: 'Please select activity resource',
      trigger: 'change',
    },
  ],
  desc: [{ required: true, message: 'Please input activity form', trigger: 'blur' }],
});

const patchList = [
  {
    id: 1,
    name: 'home.fullSticker',
  },
  {
    id: 2,
    name: 'home.topLevel',
  },
  {
    id: 3,
    name: 'home.groundFloor',
  },
];

const submitForm = () => {
  const token = JSON.parse(localStorage.getItem('loginIfo')) || {};
  if (token.accessToken) {
    router.push({
      path: '/pricing/pcb',
      query: {
        productId: pcbData.productId, // 板子类型
        boardLayer: pcbData.boardLayer, // 板子层数
        pcbLength: pcbData.pcbLength, // 板子长度
        pcbWidth: pcbData.pcbWidth, // 板子宽度
        orderNumber: pcbData.orderNumber, // 数量
      },
    });
  } else {
    router.push({
      path: '/login',
    });
  }
};

const smtSubmitForm = () => {
  const token = JSON.parse(localStorage.getItem('loginIfo')) || {};
  if (token.accessToken) {
    router.push({
      path: '/pricing/smt',
      query: {
        smtLayer: pcbData.smtLayer,
        orderNumber: pcbData.orderNumber,
        // smtSolderJoint: pcbData.smtSolderJoint,
        // patchType: pcbData.patchType,
      },
    });
  } else {
    router.push({
      path: '/login',
    });
  }
};
const resetForm = (formEl: { resetFields: () => void }) => {
  if (!formEl) return;
  formEl.resetFields();
};

const options = Array.from({ length: 10 }).map((_, idx) => ({
  value: `${idx + 1}`,
  label: `${idx + 1}`,
}));

/**
 * 选择板子数量
 * @param item
 */
const selectCountHandle = (item: number) => {
  pcbData.orderNumber = item;
  isHideMore.value = false;
  boardNum.value = '';
};

/**
 * 获取更多数量
 *
 */
const handleMore = () => {
  isHideMore.value = true;
  console.log('handleMore');
};

const addNoardNum = () => {
  if (!boardNum.value) {
    ElMessage.error(t('mall.quantity_cannot_be_empty'));
    return;
  }
  pcbData.orderNumber = boardNum.value;
  dropdown.value.handleClose();

  // let num = Number(boardNum.value);
  // pcbRuleForm.countList.push(num);
};

const selectAtive = (val: boolean) => {
  isHideMore.value = false;
  boardNum.value = '';
  pcbRuleForm.isAtive = val;
};

/**
 * 获取产品分类列表
 */
const getProductList = () => {
  getDictTypeList({
    businessType: 1,
  }).then((res) => {
    if (res.code === 200) {
      pcbData.productList = res.data;
    }
  });
};

/**
 * 获取PCB工艺分类列表
 */
const getPcbCraftsCategoryList = () => {
  queryCraftsCategoryList({
    businessType: 1,
  }).then((res) => {
    if (res.code === 200) {
      if (res.data && Array.isArray(res.data)) {
        const layerConfig = res.data.find((item) => item.mainCategory === 1);
        if (layerConfig) {
          pcbData.layerList = layerConfig.children;
        }
      }
    } else {
      // ElMessage.error(res.msg);
    }
  });
};

const handleClose = (visible) => {
  if (!dropdown.value) return;
  if (visible) {
    dropdown.value.handleClose();
  }
};
/**
 * 获取层数
 */
const getNumberLayers = () => {
  // const arr = [];
  // data.forEach((item) => {
  //   if (item.mainCategory == 1) {
  //     arr.push(item);
  //   }
  // });

  // arr[0].crmPcbaCraftsCategoryDetailVOS.sort((a, b) => {
  //   return a.craftsDetailName - b.craftsDetailName;
  // });
  // pcbData.pcbCraftsCategoryList = arr[0].crmPcbaCraftsCategoryDetailVOS;
  // pcbData.displayData = arr[0].crmPcbaCraftsCategoryDetailVOS.slice(0, 5);
  // pcbData.layerList = arr[0].crmPcbaCraftsCategoryDetailVOS.slice(
  //   6,
  //   arr[0].crmPcbaCraftsCategoryDetailVOS.length,
  // );
  console.log('PCB工艺分类列表', pcbData.layerList);
};

const smtLayerHandle = (item) => {
  console.log('item', item);
  pcbData.smtLayer = item;
};

// const selectHandle = (item) => {
//   pcbData.boardLayer = item;
//   pcbData.boardLayers = '';
// };

onMounted(() => {
  getProductList();
  getPcbCraftsCategoryList();
});
</script>
<template>
  <div class="pricing-form">
    <el-tabs type="border-card">
      <el-tab-pane label="PCB">
        <el-form
          ref="ruleFormRef"
          inline
          :model="pcbData"
          label-width="120px"
          label-position="top"
          hide-required-asterisk
        >
          <el-form-item :label="$t('home.boardType')" prop="count">
            <el-select
              style="width: 160px"
              v-model="pcbData.productId"
              :placeholder="$t('home.boardType')"
            >
              <el-option
                v-for="item in pcbData.productList"
                :key="item.value"
                :label="item.name"
                :value="item.categoryId"
              />
            </el-select>
          </el-form-item>
          <el-form-item :label="$t('home.boardLayer')" prop="count">
            <el-row type="flex" align="center">
              <el-select
                style="width: 130px"
                v-model="pcbData.boardLayer"
                :placeholder="$t('home.more')"
              >
                <el-option
                  v-for="item in pcbData.layerList"
                  :key="item.id"
                  :label="item.craftsName"
                  :value="item.craftsName"
                />
              </el-select>
            </el-row>
          </el-form-item>
          <el-form-item :label="$t('home.boardSize')" prop="count">
            <el-input v-model="pcbData.pcbLength" v-number style="width: 80px" maxlength="8" />
            <span style="padding: 0 10px"
              ><el-icon><CloseBold /></el-icon
            ></span>
            <el-input v-model="pcbData.pcbWidth" v-number style="width: 80px" />
            <span style="padding-left: 10px">cm</span>
          </el-form-item>
          <el-form-item :label="$t('home.boardSum')" prop="count">
            <el-dropdown
              trigger="click"
              @command="selectCountHandle"
              @visible-change="selectAtive"
              ref="dropdown"
            >
              <div :class="pcbRuleForm.isAtive ? 'active' : 'count-but'">
                <span>{{ pcbData.orderNumber }}</span>
                <el-icon><ArrowDown /></el-icon>
              </div>
              <template #dropdown>
                <el-dropdown-menu>
                  <el-dropdown-item
                    v-for="(item, index) in pcbRuleForm.countList"
                    :key="index"
                    :command="item"
                    >{{ item }}</el-dropdown-item
                  >
                  <span class="more" @click="handleMore">{{ $t('home.more') }}</span>
                </el-dropdown-menu>

                <el-input
                  :placeholder="$t('mall.enter_quantity')"
                  v-show="isHideMore"
                  v-number="'integer'"
                  v-model="boardNum"
                  size="mini"
                  style="margin-top: 10px"
                />
                <div
                  style="margin-top: 10px; display: flex; justify-content: flex-end; width: 100%"
                >
                  <el-button @click="addNoardNum" v-show="isHideMore" type="primary" size="small"
                    >确认</el-button
                  >
                </div>
              </template>
            </el-dropdown>
          </el-form-item>
          <div class="pricing-btn-wrap">
            <el-button
              type="primary"
              @click="submitForm()"
              style="margin-top: 10px; margin-left: 0px"
              class="immediate-pricing"
            >
              {{ $t('home.priceImmediately') }}
            </el-button>
          </div>
        </el-form>
      </el-tab-pane>
      <el-tab-pane label="SMT">
        <el-form
          ref="ruleFormRef"
          inline
          :model="smtRuleForm"
          label-width="120px"
          label-position="top"
          hide-required-asterisk
        >
          <el-form-item prop="smtLayer">
            <template #label>
              <span style="padding-right: 5px; color: red">*</span>
              {{ $t('home.SMDLayer') }}
            </template>
            <el-select
              style="width: 118px"
              v-model="pcbData.smtLayer"
              :placeholder="$t('home.SMTNumberLayers')"
              @change="smtLayerHandle"
            >
              <el-option
                v-for="item in patchList"
                :key="item.id"
                :label="$t(item.name)"
                :value="item.id"
              />
            </el-select>
          </el-form-item>
          <el-form-item :label="$t('smt.patchQuantity')" prop="count">
            <el-input type="text" class="smt-input" v-number v-model="pcbData.orderNumber" />
            <el-button type="primary" @click="smtSubmitForm()" class="immediate-pricing">
              {{ $t('home.priceImmediately') }}
            </el-button>
          </el-form-item>

          <!-- <div class="pricing-btn-wrap">
            <el-button type="primary" class="m-60" @click="smtSubmitForm()">
              {{ $t('home.priceImmediately') }}
            </el-button>
          </div> -->
        </el-form>
      </el-tab-pane>
    </el-tabs>
  </div>
</template>
<style lang="scss" scoped>
.smt-input {
  width: 118px;
}
.m-8 {
  margin: 0 12px 0 8px;
}
.m-60 {
  position: absolute;
  right: 60px;
}
.pricing-form {
  // --el-border-color: var(--mall-text-color-primary) !important;

  .pricing-btn-wrap {
    display: flex;
    align-items: center;
  }

  .layer-radio-group {
    margin-right: 8px;
    ::v-deep .el-radio {
      &.is-bordered {
        display: flex;
        justify-content: center;
        width: 40px;
        height: 40px;
        border-radius: 4px;
        background: #ffffff;

        > .el-radio__label {
          color: var(--mall-text-color-primary);
        }
        &.is-checked {
          background: #5255fe;
          border: none;
          > .el-radio__label {
            color: #fff;
          }
          &:after {
            background-image: none !important;
          }
        }
      }
    }
  }

  ::v-deep .el-tabs--border-card {
    border: none;
    border-radius: 8px;
    background: #ffffff;
    box-shadow: 0 0 14px 0 #f2f2fa;
    --el-tabs-header-height: 44px;
    height: 160px;
    > .el-tabs__header {
      background: #fff;
      border: none;
      & .is-active {
        border-right-color: var(--mall-header-bg);
        border-left-color: var(--mall-header-bg);
      }

      .el-tabs__nav {
        background: #e5e5e5;
        color: var(--mall-text-color-primary);
        font-size: 16px;
        font-weight: 500;
        transition: none;
        .el-tabs__item {
          width: 150px;
        }
      }
    }
  }
}

.immediate-pricing {
  margin-left: 32px;
  height: 40px !important;
}

::v-deep .el-input__inner {
  height: 40px;
}

.el-select-v2__wrapper {
  height: 48px !important;
}
.count-but {
  width: 110px;
  height: 40px;
  border-radius: 4px;
  line-height: 40px;
  text-align: center;
  border: 1px solid var(--mall-border-color);
  background: #ffffff;
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 0 12px;
  box-sizing: border-box;
}
.active {
  width: 110px;
  height: 40px;
  border-radius: 4px;
  line-height: 40px;
  text-align: center;
  border: 1px solid var(--mall-color-primary);
  background: #ffffff;
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 0 12px;
  box-sizing: border-box;
}
.more {
  width: 56px;
  height: 29px;
  border-radius: 4px;
  opacity: 1;
  background: #f0f0ff;
  line-height: 29px;
  text-align: center;
  cursor: pointer;
}
:global(.el-dropdown__popper .el-dropdown__list) {
  width: 284px;
  height: 282px;
  padding: 12px 12px;
}
:global(.el-dropdown-menu) {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(56px, 1fr));
  grid-gap: 12px;
  ul {
    width: 100%;
  }
}
:global(.el-dropdown-menu__item) {
  width: 56px;
  height: 29px;
  border-radius: 4px;
  background: #f0f0ff;
  padding: 0 !important;
  justify-content: center;
  color: #5255fe;
  font-size: 14px;
}
</style>
